<?php

class CartController extends Controller {
	public function actionIndex(){
		$criteria = new CDbCriteria();
		$criteria->order = "RAND()";
		$random_category = Category::model()->find($criteria);
        $this->yiistoRender('index', array(
     	    'random_category' => $random_category,
     	));
	}
	
	public function actionGetWidget(){
        if(Yii::app()->request->isAjaxRequest){
            return $this->widget('Cart');
      	}else{
      		$fullPath = base64_decode($_POST['fullPath']);
      		Yii::app()->request->redirect($fullPath);
      	}
	}
	
	public function actionUpdate(){

		if(!isset($_POST['id']) || !isset($_POST['action']) || !isset($_POST['fullPath'])){
			return false;
		}

		$fullPath = base64_decode($_POST['fullPath']);
		$id = base64_decode($_POST['id']);
		$action = base64_decode($_POST['action']);
		
		$item = Item::model()->findByPk($id);
		if($item->countInCart()){
			$quantity = $item->countInCart();
			if($action == 'add') $quantity = $quantity+1;
			if($action == 'decrement') $quantity = $quantity-1;
		}else{
			$quantity = 0;
			if($action == 'add') $quantity = 1;
		}
		if($action == 'remove') $quantity = 0;

		Yii::app()->shoppingCart->update($item,$quantity);

        $this->redirectOrReturnTrue($fullPath);
	}
	
	public function actionClear(){
		Yii::app()->shoppingCart->clear();
        $fullPath = base64_decode($_POST['fullPath']);
        $this->redirectOrReturnTrue($fullPath);
	}

	// Uncomment the following methods and override them if needed
	/*
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'inlineFilterName',
			array(
				'class'=>'path.to.FilterClass',
				'propertyName'=>'propertyValue',
			),
		);
	}

	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
	*/
}